/**
 * Copyright (c) 2018 软唐 All rights reserved.
 *
 * https://www.softtown.cn
 *
 * 版权所有，侵权必究！
 */

package com.softtown.modules.security.service.impl;

import com.softtown.modules.security.dao.SysUserTokenDao;
import com.softtown.modules.security.entity.SysUserTokenEntity;
import com.softtown.modules.security.service.ShiroService;
import com.softtown.modules.security.user.UserDetail;
import com.softtown.modules.sys.dao.SysMenuDao;
import com.softtown.modules.sys.dao.SysUserDao;
import com.softtown.modules.sys.entity.SysUserEntity;
import java.util.ArrayList;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Resource
    private SysMenuDao sysMenuDao;
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysUserTokenDao sysUserTokenDao;


    @Override
    public Set<String> getUserPermission(UserDetail user,Long adminUserId,Long compId) {
        //系统管理员，拥有最高权限
        List<String> permissionsList = new ArrayList<>();
        if(adminUserId.equals(user.getId())){
            permissionsList = sysMenuDao.getAdminPermissionsList(compId);
        }else {
            permissionsList = sysMenuDao.getUserPermissionsList(user.getId());

        }

        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String permissions : permissionsList){
            if(StringUtils.isBlank(permissions)){
                continue;
            }
            permsSet.addAll(Arrays.asList(permissions.trim().split(",")));
        }

        return permsSet;
    }


    @Override
    public Set<String> getUserPermissions(UserDetail user) {
        //系统管理员，拥有最高权限
        List<String> permissionsList ;
            permissionsList = sysMenuDao.getUserPermissionsList(user.getId());


        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String permissions : permissionsList){
            if(StringUtils.isBlank(permissions)){
                continue;
            }
            permsSet.addAll(Arrays.asList(permissions.trim().split(",")));
        }

        return permsSet;
    }

    @Override
    public SysUserTokenEntity getByToken(String token) {
        return sysUserTokenDao.getByToken(token);
    }

    @Override
    public SysUserEntity getUser(Long userId) {
        return sysUserDao.selectById(userId);
    }


}